package com.millstein.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.millstein.context.UserAuthorization;
import com.millstein.enums.BizCodeEnum;
import com.millstein.enums.user.DefaultAddressEnum;
import com.millstein.exception.BizException;
import com.millstein.model.AddressDO;
import com.millstein.mapper.AddressMapper;
import com.millstein.model.LoginUser;
import com.millstein.request.AddressAddRequest;
import com.millstein.service.AddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.millstein.vo.AddressVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 电商-公司收发货地址表 服务实现类
 * </p>
 *
 * @author millstein
 * @since 2021-09-08
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, AddressDO> implements AddressService {

    /**
     * 新增收货地址
     *
     * @param addressAddRequest 收货地址信息
     */
    @Override
    @Transactional
    public void add(AddressAddRequest addressAddRequest) {
        AddressDO addressDO = new AddressDO();
        BeanUtils.copyProperties(addressAddRequest, addressDO);

        LoginUser loginUser = UserAuthorization.getUserContext();
        addressDO.setUserId(loginUser.getId());
        addressDO.setCreateTime(new Date());

        // 新增的是默认收货地址
        if (addressAddRequest.getDefaultStatus().equals(DefaultAddressEnum.DEFAULT_ADDRESS.getCode())) {
            // 查询这个用户原先有没有默认收货地址信息
            List<AddressDO> defaultAddresses = this.list(new QueryWrapper<AddressDO>()
                    .eq("default_status", DefaultAddressEnum.DEFAULT_ADDRESS.getCode())
                    .eq("user_id", loginUser.getId()));
            // 如果有的话，要将原来的默认收货地址都改为普通地址
            if (CollectionUtil.isNotEmpty(defaultAddresses)) {
                for (AddressDO dbItem : defaultAddresses) {
                    dbItem.setDefaultStatus(DefaultAddressEnum.NORMAL_ADDRESS.getCode());
                    if (!this.updateById(dbItem)) {
                        throw new BizException(BizCodeEnum.SAVE_FAILURE);
                    }
                }
            }
        }

        // 保存新增的记录
        if (!this.save(addressDO)) {
            throw new BizException(BizCodeEnum.SAVE_FAILURE);
        }
    }

    /**
     * 根据id查询收货地址信息
     *
     * @param id 收货地址id
     * @return
     */
    @Override
    public AddressVO findById(Long id) {
        AddressDO dbAddress = this.getById(id);
        // 防范越权攻击
        if (!dbAddress.getId().equals(UserAuthorization.getUserContext().getId())) {
            dbAddress = null;
        }
        return dbAddress == null ? null : new AddressVO(dbAddress);
    }


    @Override
    public List<AddressVO> findList() {
        LoginUser loginUser = UserAuthorization.getUserContext();
        QueryWrapper<AddressDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", loginUser.getId());
        List<AddressDO> list = this.list(wrapper);

        if (CollectionUtil.isEmpty(list)) {
            return new ArrayList<>();
        }

        List<AddressVO> voList = new ArrayList<>();
        for (AddressDO addressDO : list) {
            voList.add(new AddressVO(addressDO));
        }
        return voList;
    }

    /**
     * 删除收货地址
     *
     * @param id 收货地址id
     */
    @Override
    public void delete(Long id) {
        // 防范越权攻击
        QueryWrapper<AddressDO> wrapper = new QueryWrapper<AddressDO>().eq("id", id).eq("user_id",
                UserAuthorization.getUserContext().getId());
        if (!this.remove(wrapper)) {
            throw new BizException(BizCodeEnum.DELETE_FAILURE);
        }
    }
}
